﻿using MS.Utility.Config;
using MS.Utility.Logging;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Mail;
using System.Text;

namespace MS.Utility.Email
{
    public class EmailHelper
    {
        /// <summary>
        /// 邮件发送
        /// </summary>
        /// <param name="mailTo">接收方</param>
        /// <param name="subject">邮件标题</param>
        /// <param name="content">邮件内容</param>
        /// <returns></returns>
        public static bool MailSend(string mailTo, string subject, string content)
        {
            try
            {
                SmtpClient smtp = new SmtpClient();
                smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
                smtp.EnableSsl = false;
                smtp.Host = EmailConfig.MailSmtp;
                smtp.Port = EmailConfig.MailPort;
                smtp.UseDefaultCredentials = true;
                smtp.Credentials = new NetworkCredential(EmailConfig.SentMail, EmailConfig.MailPwd);
                MailMessage mm = new MailMessage();
                mm.From = new MailAddress(EmailConfig.SentMail, EmailConfig.MailShowName, Encoding.GetEncoding(936));

                foreach (var item in mailTo.Split(','))
                {
                    mm.To.Add(item);
                }

                mm.Subject = subject;
                mm.SubjectEncoding = Encoding.GetEncoding(936);
                mm.IsBodyHtml = true;
                mm.BodyEncoding = Encoding.GetEncoding(936);
                mm.Body = content;
                smtp.Send(mm);
            }
            catch (Exception ex)
            {
                LogHelper.Error(ex);
                throw ex;
            }
            return true;
        }


        #region 取发邮件的模板文件
        /// <summary>
        /// 取发邮件的模板文件
        /// </summary>
        /// <param name="templateName">模板名称</param>
        /// <returns>字符串形式的值</returns>
        public static string ReadMailTemplate(string templateName)
        {
            string file;
            string templatefile = System.Web.Hosting.HostingEnvironment.MapPath("/Templates/" + templateName);
            StreamReader sr = new StreamReader(templatefile, System.Text.Encoding.Default);
            try
            {
                file = sr.ReadToEnd();
            }
            catch (Exception ex)
            {
                throw new Exception(ex.ToString());
            }
            finally
            {
                sr.Close();
            }
            return file;
        }
        #endregion
        
    }
}
